package com.yc.testupload.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.yc.testupload.dao.UserDAO;
import com.yc.testupload.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 获取用户ID的Servlet
 * 用于根据用户名获取实际的用户ID
 */
@WebServlet("/get-user-id")
public class GetUserIdServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(GetUserIdServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        try {
            // 获取用户名参数
            String username = request.getParameter("username");
            logger.debug("接收到获取用户ID的请求，用户名: {}", username);

            // 参数验证
            if (username == null || username.isEmpty()) {
                logger.warn("获取用户ID失败：用户名为空");
                out.write("{\"code\":1,\"message\":\"用户名为空\",\"userId\":null}");
                return;
            }

            // 使用UserDAO根据用户名获取用户信息
            UserDAO userDAO = new UserDAO();
            User user = userDAO.getUserByUsername(username);

            if (user != null) {
                int userId = user.getUserId();
                logger.debug("成功获取用户ID: {} 对应用户名: {}", userId, username);
                out.write(String.format("{\"code\":0,\"userId\":%d,\"username\":\"%s\"}", userId, username));
            } else {
                logger.warn("未找到用户: {}", username);
                out.write(String.format("{\"code\":1,\"message\":\"未找到用户\"}", username));
            }
        } catch (Exception e) {
            logger.error("获取用户ID过程中发生错误: {}", e.getMessage(), e);
            out.write("{\"code\":500,\"message\":\"系统错误，请稍后重试\",\"userId\":null}");
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 对于POST请求，同样处理
        doGet(request, response);
    }
}